package com.cloudpivot.receivales.invoice.util;

import org.springframework.context.annotation.Bean;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


public class RsaEncryptionUtil {

    public Map<String,byte[]> rsaEncryption(String code, String password){
        byte[] encryptedcode = new byte[0];
        byte[] encryptedpassword = new byte[0];
        try {
            encryptedcode = encryptWithRSAPublicKey(code, getRSAPublicKey());
            encryptedpassword = encryptWithRSAPublicKey(password, getRSAPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,byte[]> map = new HashMap<>();
        map.put("code", encryptedcode);
        map.put("password",encryptedpassword);
        return map;
    }

    public static byte[] encryptWithRSAPublicKey(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }

    public static PublicKey getRSAPublicKey() throws Exception {
        // 从文件或其他地方获取公钥字符串
        String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCfoGXxmp9iyM6g9XYq5f26/oDdhkSyVP0y77rR4eZ2T4+oZ8oqH+RbHQLwZGCALrydOf+giPxy5LpfzHQkFVHyqlRXZKhjtfGV+y8PaV595jVnoqVMemrLPIUpeZ9VUa0mIj1dgCByrGfyf87m83Zu1xxD2HD2ZpZYvboHh/qQwIDAQAB";

        byte[] encodedPublicKey = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedPublicKey);
        KeyFactory factory = KeyFactory.getInstance("RSA");

        return factory.generatePublic(spec);
    }
}
